package com.spring.picture.service.impl;

import com.spring.picture.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSenderImpl mailSender;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public void sendMail(String email) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();

        // 生成验证码，并将验证码写入redis，设置过期时间为5分钟
        String code = randomCode();
        redisTemplate.opsForValue().set(email, code, 5, TimeUnit.MINUTES);

        simpleMailMessage.setSubject("验证码邮件"); // 主题
        simpleMailMessage.setText("您收到的验证码是："+code); // 内容
        simpleMailMessage.setFrom(from); // 发件人
        simpleMailMessage.setTo(email); // 收件人
        mailSender.send(simpleMailMessage); // 发送

        return ;
    }

    /**
     * 随机生成6位数的验证码
     * @return String code
     */
    public String randomCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for(int i = 0;i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }
}
